var util = require('../../utils/util.js');
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    p_order_id : 0,
    record_status: 0,
    recording_image: "/images/luyin_point.png",
    send_image: "/images/send_voice.png",
    voice_button_msg: "按住 说话",
    recording: "正在 录音",
    
    description_type: 1,
    description_voice: "",
    upload_images: [],
    description: "",
    desc_count: 0,
    orderInfo : {},

    j: 1,//帧动画初始图片  
    isSpeaking: false,//是否正在说话  
    voices: [],//音频数组  
    imagePath: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    // 设置全局图片路径
    this.setData({
      imagePath: app.globalData.imagePath,
      send_image: app.globalData.imagePath + '/send_voice.png',
      recording_image: app.globalData.imagePath + "/luyin_point.png",
    });
    
    var order_id = options.id;
    this.setData({
      p_order_id: order_id,
      apiUrl: app.globalData.apiUrl
    });

    if (app.globalData.position) {
      this.setData({
        position: app.globalData.position,
      });
    } else if (this.data.canIUse) {
      app.positionReadyCallback = position => {
        this.setData({
          position: position
        })
      }
    };

    this.getOrderInfo();


    var that = this;
    this.recorderManager = wx.getRecorderManager();

    this.recorderManager.onStart(function () {
      speaking.call(that);
      recordImageflash.call(that);
      that.setData({
        isSpeaking: true,
        voice_button_msg: "松开 结束",
        record_status: 1
      })
    });

    this.recorderManager.onError(function () {
      app.checkAuthRecord();
      that.tip("录音失败！", "none");
    });

    this.recorderManager.onStop(function (res) {
      that.setData({
        description_voice: res.tempFilePath,
        record_status: 2
      })
      that.tip("录音完成！")
    });

    this.innerAudioContext = wx.createInnerAudioContext();
    this.innerAudioContext.onError((res) => {
      that.tip("播放录音失败！", "none");
    });

    // 播放结束时触发
    this.innerAudioContext.onStop((res) => {
      
    });

    // 音频自然播放结束事件
    this.innerAudioContext.onEnded((res) => {
      that.setData({
        toPlay: '',
        isPlay: false
      });
    });

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  // 打开地图选择位置
  toMap: function () {
    wx.chooseLocation({
      success: res => {
        app.globalData.latitude = res.latitude;
        app.globalData.longitude = res.longitude;
        app.globalData.position = res.name;

        this.setData({
          position: res.name
        });
      },
      fail: res => {
        app.reportError(res.errMsg, 'toJoin-toMap-wx.chooseLocation');
        app.checkAuthUserLocation();
      }
    })
  },
  // 切换描述方式
  changeSendMethod: function (e) {
    app.checkAuthRecord();

    var change_image = app.globalData.imagePath + "/send_character.png";
    if (this.data.description_type == 2) {
      change_image = app.globalData.imagePath + "/send_voice.png";
      this.data.description_type = 1;
    } else {
      this.data.description_type = 2;
    }

    this.setData({
      send_image: change_image,
      description_type: this.data.description_type
    });
  }

  /**
 * 录制mp3音频
*/
  , startRecordMp3: function () {
    this.recorderManager.start({
      format: 'mp3'
    });
  }

  /**
   * 停止录音
   */
  , stopRecord: function () {
    
    this.recorderManager.stop();

  }
  /**
   * 暂停播放
   */
  , stopPlayRecord: function () {

    this.innerAudioContext.stop();

    this.setData({
      toPlay: '',
      isPlay: false
    });
  }
  /**
   * 播放录音
   */
  , playRecord: function () {
    var that = this;
    var description_voice = this.data.description_voice;
    if (description_voice == '') {
      this.tip("请先录音！")
      return;
    }
    this.innerAudioContext.src = this.data.description_voice;
    this.innerAudioContext.play()

    this.setData({
      toPlay: description_voice,
      isPlay: true
    });
  }
  /**
  * 删除录音
  */
  , deleteRecord: function (e) {
    var that = this;
    wx.showModal({
      title: '提示',
      content: '确定删除录音吗？',
      success: function (res) {
        if (res.confirm) {
          that.data.description_voice = '';
          that.setData({
            description_voice: ''
          });
        }
      }
    });
  }
  /**
  * 提示
  */
  , tip: function (msg, status = 'success') {
    wx.showToast({
      title: msg,
      icon: status,
      duration: 1000
    });
  }
  , bindTextAreaBlur: function (e) {
    this.setData({
      description: e.detail.value,
    });
  },
  descConfirm: function (e) {
    var desc_length = 60;
    var desc = e.detail.value;
    if (desc.length > desc_length) {
      desc = desc.substring(0, desc_length);
      
      this.setData({
        description: desc,
      });
    }

    this.setData({
      desc_count: desc.length,
      description: e.detail.value
    });
  }
  
  /**
  * 图片上传
  * */
  , uploadImage: function () {
    var count = 9 - this.data.upload_images.length;
    wx.chooseImage({
      count: count,                             // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'],      // 可以指定来源是相册还是相机，默认二者都有
      success: res => {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths
        var upload_images = this.data.upload_images;
        for (var i = 0; i < tempFilePaths.length; i++) {
          upload_images.push(tempFilePaths[i]);
        }

        this.setData({
          upload_images: upload_images
        });

      }
    })
  }

  /**
   * 删除图片
   */
  , deleteImage: function (e) {

    var id = e.currentTarget.id;
    var that = this;
    wx.showModal({
      title: '提示',
      content: '确定删除吗？',
      success: function (res) {
        if (res.confirm) {
          that.data.upload_images.splice(id, 1);
          that.setData({
            upload_images: that.data.upload_images
          });
        }
      }
    });
  }

  /**
   * 参与用户提交拼单信息
   */
  , formSubmit: function (e) {
    var that = this;

    // 判断描述不能为空
    if ('' == that.data.description_voice && '' == that.data.description) {
      wx.showToast({
        title: '请填写拼单文字或语音！',
        icon: 'none',
        duration: 2000
      });
      return false;
    }

    wx.showToast({
      icon: "loading",
      title: "正在提交"
    });

    var order_id = 0;
    var p_order_id = that.data.p_order_id;
    const requestTask = wx.request({
      url: app.globalData.apiUrl + 'order/joinOrder', //仅为示例，并非真实的接口地址
      method: 'POST',
      data: {
        p_order_id : that.data.p_order_id,
        description_type: that.data.description_type,
        description: that.data.description,
        latitude: app.globalData.latitude,
        longitude: app.globalData.longitude,
        position: app.globalData.position,
        form_id: e.detail.formId
      },
      header: {
        "Content-Type": "application/x-www-form-urlencoded",
        "Cookie": "PHPSESSID=" + wx.getStorageSync('sessionID')
      },
      success: function (res) {
        
        if (res.data.code > 10000) {
          wx.showToast({
            title: '提交失败，请重试！',
            icon: 'none'
          });
        } else {
          order_id = res.data.message;

          // 将录音文件合并到图片数组中统一上传
          if (that.data.description_voice != '') {
            var i = that.data.upload_images.length;
            that.data.upload_images[i] = that.data.description_voice;
          }

          // 提交图片和录音
          var images = that.data.upload_images;
          var images_length = images.length;
          if (images_length <= 0) {
            wx.showToast({
              title: '提交成功！',
              icon: 'success',
              duration: 2000,
              complete: function () {
                setTimeout(function () {
                  wx.redirectTo({
                    url: '/pages/detail/detail?id=' + p_order_id,
                  });
                }, 2000);
              }
            });
          }
          for (var i = 0; i < images_length; i++) {
            wx.uploadFile({
              url: app.globalData.apiUrl + 'order/uploadImageVoice', 
              header: {
                'content-type': 'multipart/form-data',
                'Cookie': 'PHPSESSID=' + wx.getStorageSync('sessionID')
              },
              filePath: encodeURI(images[i]),
              name: 'file',
              formData: {
                'order_id': encodeURI(order_id)
              },
              success: function (res) {
                wx.showToast({
                  title: '提交成功！',
                  icon: 'success',
                  duration: 2000,
                  complete: function () {
                    setTimeout(function () {
                      wx.redirectTo({
                        url: '/pages/detail/detail?id=' + p_order_id,
                      });
                    }, 2000);
                  }
                });
              },
              fail: function (res) {
                
                wx.showModal({
                  title: '提示',
                  content: '图片上传失败!',
                  showCancel: false
                });

                app.reportError(res.errMsg, 'toJoin-formSubmit-order/uploadImageVoice');
              }
            });
          }
        }
      },
      fail: function (res) {

        app.reportError(res.errMsg, 'toJoin-formSubmit-order/joinOrder');
        wx.showToast({
          title: '提交失败，请重试！',
          icon: 'none',
          duration: 2000
        });
      }
    })

    // requestTask.abort() // 取消请求任务
  },
  /**
   * 获取订单信息
   */
  getOrderInfo : function(){
    var that = this;
    wx.request({
      url: app.globalData.apiUrl + 'index/info',
      header: {
        'content-type': 'application/json'
      },
      data: {
        id: that.data.p_order_id
      },
      success: function (res) {
        if (res.data.code == 10000) {
          that.setData({
            orderInfo: res.data.message,
            imageList: res.data.message.image_list
          });
        } else {
          that.data.orderInfo = {};
        }
      }
    })
  }

  /**
   * To Home Page
   */
  , toHome: function (e) {
    app.formIdSubmit(e);
    wx.switchTab({
      url: '/pages/index/index',
    });
  }
  /**
   * To My Page
   */
  , toMy: function (e) {
    app.formIdSubmit(e);
    wx.switchTab({
      url: '/pages/center/center',
    });
  }
})

// 录音展示图片动态闪烁
function recordImageflash() {
  var _this = this;
  var i = 1;
  this.timer = setInterval(function () {
    i++;
    i = i % 2;
    var image_patch = "";
    if (i == 0) {
      image_patch = app.globalData.imagePath + "/luyin_point.png";
    }
    _this.setData({
      recording_image: image_patch,
    })
  }, 600);
}

//麦克风帧动画
function speaking() {
  var _this = this;
  //话筒帧动画
  var i = 1;
  this.timer = setInterval(function () {
    i++;
    i = i % 5;
    _this.setData({
      j: i
    })
  }, 200);
}

var t = Date.now();
function sleep(d) {
  while (Date.now - t <= d);
}